import 'package:bigegg/dialog/xmm_business_dialog.dart';
import 'package:bigegg/entity/articel/xmm_article_info.dart';
import 'package:bigegg/global/routes/xmm_routes.dart';
import 'package:bigegg/page/article/detail/xmm_article_detail_controller.dart';
import 'package:bigegg/res/xmm_img.dart';
import 'package:bigegg/widget/image/xmm_circle_cached_network_image.dart';
import 'package:bigegg/widget/xmm_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class XmmArticleDetailPage extends StatefulWidget {
  const XmmArticleDetailPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return XmmArticleDetailPageState();
  }
}

class XmmArticleDetailPageState extends State<XmmArticleDetailPage> {
  XmmArticleDetailController controller = Get.find<XmmArticleDetailController>();

  final ScrollController _scrollController = ScrollController();

  final _textController = TextEditingController();

  final _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _textController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          SizedBox(
            height: 440.w,
            child: bgWidget(controller.articleInfo.value.content ?? []),
          ),
          Positioned.fill(
            child: Container(
              alignment: Alignment.bottomCenter,
              child: Image.asset(
                width: double.infinity,
                "assets/images/xmm_article_detail_bg.png",
                fit: BoxFit.fitWidth,
              ),
            ),
          ),
          toolBarWidget(
            context,
            "",
            rightImage: controller.isMine ? null : XmmImg.moreIcon,
            boxColor: controller.isMine ? Colors.transparent : Colors.white,
            onRightTap: () => showMoreDialog(),
          ),
          Obx(() => contentWidget(controller.articleInfo.value)),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: AnimatedPadding(
              padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
              duration: const Duration(milliseconds: 10),
              child: sendCommentWidget(),
            ),
          ),
        ],
      ),
    );
  }

  void showMoreDialog() {
    XmmBusinessDialog.showMoreDialog(controller.articleInfo.value.wallUser?.userId ?? "");
  }

  void showSendGiftDialog() {
    XmmBusinessDialog.showSendGiftDialog(controller.articleInfo.value.wallUser!);
  }

  Widget bgWidget(List<String> content) {
    var widgets = content.map((e) => Image.asset(e, fit: BoxFit.cover));
    return PageView(children: widgets.toList());
  }

  Widget contentWidget(XmmArticleInfo articleInfo) {
    return Container(
      margin: EdgeInsets.only(top: 292.w + context.mediaQueryPadding.top, bottom: 90.w),
      padding: const EdgeInsets.only(left: 20, right: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: [
          headWidget(articleInfo),
          const SizedBox(height: 10),
          Text(
            articleInfo.title ?? "",
            style: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF202020),
            ),
          ),
          const SizedBox(height: 5),
          Text(
            controller.articleDescription.value,
            style: TextStyle(
              fontSize: 12.sp,
              color: const Color(0xFF454545),
            ),
          ),
          const SizedBox(height: 14),
          toolWidget(articleInfo),
          const SizedBox(height: 28),
          commentListWidget(articleInfo),
        ],
      ),
    );
  }

  Widget headWidget(XmmArticleInfo articleInfo) {
    return Row(
      children: [
        GestureDetector(
          onTap: () => XmmRoutes.routePersonPage(articleInfo.wallUser?.userId ?? ""),
          child: CachedNetworkImage(
            width: 44.w,
            height: 44.w,
            imageUrl: articleInfo.wallUser?.getAvatarUrl ?? "",
            imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                image: DecorationImage(image: imageProvider, fit: BoxFit.cover),
                border: Border.all(color: Colors.white, width: 1),
              ),
            ),
            placeholder: (context, url) => const CircularProgressIndicator(),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                articleInfo.wallUser?.nickname ?? "",
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 8),
              !controller.isMine
                  ? GestureDetector(
                      child: Container(
                        width: 55,
                        height: 22,
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
                        alignment: Alignment.center,
                        child: Text(
                          (articleInfo.wallUser?.isFollow ?? false) ? "Unfollow" : "Follow",
                          style: const TextStyle(
                            fontSize: 11,
                            color: Color(0xFF404040),
                          ),
                        ),
                      ),
                      onTap: () async {
                        if (articleInfo.wallUser?.isFollow ?? false) {
                          await controller.unfollow(articleInfo.wallUser?.userId ?? "");
                        } else {
                          await controller.follow(articleInfo.wallUser?.userId ?? "");
                        }
                      },
                    )
                  : Container()
            ],
          ),
        )
      ],
    );
  }

  Widget toolWidget(XmmArticleInfo articleInfo) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        GestureDetector(
          child: Image.asset(
            "assets/images/xmm_icon_translate.png",
            width: 32,
            height: 32,
          ),
          onTap: () {
            controller.translate(articleInfo.description ?? "");
          },
        ),
        const SizedBox(width: 20),
        !controller.isMine
            ? GestureDetector(
                child: Image.asset(
                  "assets/images/xmm_icon_chat.png",
                  width: 32,
                  height: 32,
                ),
                onTap: () => Get.toNamed(
                  XmmRoutes.chatPage,
                  arguments: articleInfo.wallUser?.userId,
                ),
              )
            : Container(),
        SizedBox(width: !controller.isMine ? 20 : 0),
        GestureDetector(
          child: Image.asset(
            (articleInfo.isLikeByMe ?? false) ? "assets/images/xmm_icon_like.png" : "assets/images/xmm_icon_unlike.png",
            width: 32,
            height: 32,
          ),
          onTap: () {
            if (articleInfo.isLikeByMe ?? false) {
              controller.unLike();
            } else {
              controller.like();
            }
          },
        ),
        SizedBox(width: !controller.isMine ? 20 : 0),
        !controller.isMine
            ? GestureDetector(
                child: Image.asset(
                  "assets/images/xmm_icon_send_gift.png",
                  width: 32,
                  height: 32,
                ),
                onTap: () => showSendGiftDialog(),
              )
            : Container(),
      ],
    );
  }

  Widget commentListWidget(XmmArticleInfo articleInfo) {
    return Flexible(
      child: ListView.separated(
        controller: _scrollController,
        padding: EdgeInsets.zero,
        separatorBuilder: (_, __) => const Divider(height: 10, color: Colors.transparent),
        itemCount: articleInfo.commentList?.length ?? 0,
        itemBuilder: (context, index) {
          var item = articleInfo.commentList?.elementAt(index);
          return Container(
            decoration: BoxDecoration(
              color: const Color(0xFF15E8C2),
              border: Border.all(color: Colors.white, width: 1),
              borderRadius: BorderRadius.circular(8),
            ),
            child: Container(
              height: 98,
              margin: const EdgeInsets.only(left: 12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      XmmCircleCachedNetworkImage(
                        imageUrl: item?.avatar ?? "",
                        width: 38,
                        height: 38,
                      ),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Text(
                          item?.nickname ?? "",
                          style: const TextStyle(
                            fontSize: 14,
                            color: Color(0xFF404040),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      )
                    ],
                  ),
                  const SizedBox(height: 12),
                  Text(
                    item?.content ?? "",
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xFF404040),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget sendCommentWidget() {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(
        left: 20,
        right: 20,
        bottom: MediaQuery.of(context).padding.bottom,
      ),
      height: 90.w,
      color: Colors.white,
      child: Row(
        children: [
          Expanded(
            child: Container(
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(36), color: const Color(0xFFF2F2F2)),
              padding: const EdgeInsets.only(left: 6),
              height: 36.w,
              alignment: Alignment.centerLeft,
              child: TextField(
                controller: _textController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                    borderRadius: BorderRadius.only(),
                    gapPadding: 0.0,
                  ),
                  hintText: "Enter your ideas...",
                  hintStyle: TextStyle(fontSize: 12, color: Color(0x4D000000)),
                ),
                autofocus: false,
                focusNode: _focusNode,
                onTapOutside: (e) => _focusNode.unfocus(),
              ),
            ),
          ),
          const SizedBox(width: 24),
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              width: 63,
              height: 32,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30),
                color: const Color(0xFF15E8C2),
              ),
              child: const Text(
                "Send",
                style: TextStyle(
                  fontSize: 16,
                  color: Colors.white,
                ),
              ),
            ),
            onTap: () {
              controller.sendComment(_textController.text);
              _textController.text = "";
              _focusNode.unfocus();
              Future.delayed(const Duration(milliseconds: 200), () {
                _scrollController.animateTo(
                  _scrollController.position.maxScrollExtent,
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeOut,
                );
              });
            },
          )
        ],
      ),
    );
  }
}
